
if(!isSupportCanvas()){
	alert('热力图目前只支持有canvas支持的浏览器,您所使用的浏览器不能使用热力图功能~')
}


// 判断浏览区是否支持canvas
function isSupportCanvas(){
    var elem = document.createElement('canvas');
    return !!(elem.getContext && elem.getContext('2d'));
}

var Heatmap={};
var map;

// 初始化地图
Heatmap.initMap=function(startlng,startlat){
	var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
	var top_left_navigation = new BMap.NavigationControl();  // 左上角，添加默认缩放平移控件
	var mapType1 = new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP,BMAP_HYBRID_MAP]});
 	map = new BMap.Map("heatmap",{enableMapClick:false});          // 创建地图实例
 	/* map.addControl(top_left_control); */     
	/* map.addControl(top_left_navigation); */
	map.addControl(mapType1);   
    var point = new BMap.Point(startlng, startlat);
    map.centerAndZoom(point, 15);             // 初始化地图，设置中心点坐标和地图级别
    map.enableScrollWheelZoom(); // 允许滚轮缩放
}

var maxCount=0;// 人数最多的数值

// 设置热力图的数据
Heatmap.setHeatMapData=function(data){
	var points =[];
	for (var i = 0; i < data.length; i++) {
		points.push(data[i]);
	}		
	heatmapOverlay = new BMapLib.HeatmapOverlay({"radius":50});
	map.addOverlay(heatmapOverlay);
	heatmapOverlay.setDataSet({data:points,max:maxCount});
	heatmapOverlay.show();// 显示热力图
}

// 显示区域边界
Heatmap.setPolygon=function(data){
	// 显示区域多边形
	for(var i=0;i<data.length;i++){
		var lonlatString=data[i].lonLat;
		var lonlatArray=lonlatString.split(';');
		var pointArray=new Array();
		for(var j=0;j<lonlatArray.length;j++){
			pointArray.push(new BMap.Point(lonlatArray[j].split(',')[0],lonlatArray[j].split(',')[1]));
		}
		var polygon = new BMap.Polygon(pointArray, {strokeColor:"blue", strokeWeight:1, strokeOpacity:0.0, fillOpacity: 0.0, fillColor: "none"});  
		map.addOverlay(polygon);  
	}
}

var cellUcList=new Array();
var isToday;// 是否是今天
var region; // 区域边界;
var timeArray;// 时间轴数据
Heatmap.search=function(){
		Heatmap.stopPlay();
		startIndex=0;
		ispause=false;
		var ajax = new $ax(Feng.ctxPath + "/heatmap/search", function (data) {
		Heatmap.initMap(data.areaInfo.lon, data.areaInfo.lat);
		isToday=false;
	    cellUcList=data.cellUcList;
	    maxCount=0;
	    // 获取热力图的最大值
	    cellUcList.forEach(function(elt, i) {
	    	if(elt.count>maxCount){
	    		maxCount=elt.count;
	    	}
	    })
	    if(maxCount>0){	    	
	    	$("#heatmap_blue").html("0-"+Math.floor(maxCount/5));
	    	$("#heatmap_green").html(Math.floor(maxCount/5)+1+"-"+Math.floor(maxCount/5)*2);
	    	$("#heatmap_yellow").html(Math.floor(maxCount/5)*2+1+"-"+Math.floor(maxCount/5)*3);
	    	$("#heatmap_red").html(Math.floor(maxCount/5)*3+1+"-"+Math.floor(maxCount/5)*4);
	    	$("#heatmap_result_red").html("&gt;"+Math.floor(maxCount/5)*5);
	    }
	    
		var maxHour=data.maxHour;
		var today = new Date();
		var selectDateVal=$("#time").val();
		var selectDate=selectDateVal.split('-');
		
		if(today.getFullYear()==selectDate[0]*1){
			if(today.getMonth()+1==selectDate[1]*1){
				if(today.getDate()==selectDate[2]*1){
					isToday=true;
				}
			}
		}
		region=data.subarea;
		Heatmap.setPolygon(region);
		/*
		 * if(cellUcList.length>0){ if(isToday){
		 * Heatmap.setHeatMapData(cellUcList.filter(function(elt, i) { var d =
		 * new Date(elt.time); console.log(d.getHours()==maxHour); return
		 * d.getHours()==maxHour; })); }else{
		 * Heatmap.setHeatMapData(cellUcList.filter(function(elt, i) { var
		 * time=new String(elt.time); console.log(time.substring(8,10)=="00");
		 * return time.substring(8,10)=="00"; })); } }
		 */
		
		// 初始化时间轴,如果查询是当天的数据，则默认选择最新时间，否则选择00:00
		timeArray=new Array();
		for(var t=0;t<data.timeset.length;t++){
			var timeData={};
			if(isToday){
				if(t==data.timeset.length-1){
					timeData.isSelected="true";
				}
			}else{
				if(t==0){
					timeData.isSelected="true";
				}
			}
			if(data.timeset[t].substring(3,5)!="00"){
				timeData.visibility="hidden";
			}
			timeData.nextDistance=2;
			timeData.title=data.timeset[t];
			timeData.subTitle=data.timeset[t];
			timeData.dateValue=data.timeset[t];
			timeData.pointCnt=data.timeset[t];
			timeData.bodyCnt=data.timeset[t];
			timeArray.push(timeData);
		}
		timeLineInit(timeArray);
		$(".tlnode").last().click();
		
    }, function (data) {
// Feng.error("删除失败!" + data.responseJSON.message + "!");
    });
    ajax.set("granularity",$("#granularity").val());
    ajax.set("time",$("#time").val());
    var zTreeObj = $.fn.zTree.getZTreeObj("areaTree");
    var nodes = zTreeObj.getSelectedNodes();
    if(nodes[0].level==1){    	
    	ajax.set("areaId",nodes[0].id);
    }else{
    	var parentNode=nodes[0].getParentNode();
    	ajax.set("areaId",parentNode.id);
    }
    ajax.start();
}

Heatmap.download=function(){
	html2canvas(document.querySelector("#ibox-content-map"),{
		useCORS : true
      /*
		 * foreignObjectRendering : true, allowTaint :false
		 */
	}).then(canvas => {
		var type = 'png';
		var imgData = canvas.toDataURL(type);
		// 加工image data，替换mime type
		imgData = imgData.replace(_fixType(type),'image/octet-stream');
		// 下载后的问题名
		var filename = '热力图_' + (new Date()).getTime() + '.' + type;
		// download
		saveFile(imgData,filename);
	    // Canvas2Image.saveAsPNG(canvas,canvas.width,canvas.height);
	});
} 
    
/**
 * 获取mimeType
 * 
 * @param {String}
 *            type the old mime-type
 * @return the new mime-type
 */
var _fixType = function(type) {
    type = type.toLowerCase().replace(/jpg/i, 'jpeg');
    var r = type.match(/png|jpeg|bmp|gif/)[0];
    return 'image/' + r;
};


/**
 * 在本地进行文件保存
 * 
 * @param {String}
 *            data 要保存到本地的图片数据
 * @param {String}
 *            filename 文件名
 */
var saveFile = function(data, filename){
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;
   
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
};

var ztree ;
var setting = {
		view: {
			showIcon: false,
			selectedMulti: false
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			beforeClick: beforeClick,
			onClick: onClick
		}
	};
function beforeClick(treeId, treeNode, clickFlag) {
	if(treeNode.level==0){
		return false
	}else{
		return true;
	}
}
function onClick(event, treeId, treeNode, clickFlag) {
	$("#selectArea").html(treeNode.name);
	var zTreeObj = $.fn.zTree.getZTreeObj("areaTree");
	if(treeNode.level==1){
		// window.location.href=Feng.ctxPath+"/screening?areaId="+treeNode.id+"&areaName="+treeNode.name;
		zTreeObj.selectNode(treeNode);
	}else if(treeNode.level==2){
		var parentNode=treeNode.getParentNode();
		// window.location.href=Feng.ctxPath+"/screening?areaId="+parentNode.id+"&subAreaId="+treeNode.id+"&areaName="+treeNode.name;
		zTreeObj.selectNode(parentNode);
	}
	// TODO 根据areaId跳转到景区监控
}

function showLog(str) {
	console.log(str);
}


function showIconForTree(treeId, treeNode) {
	return !treeNode.isParent;
};



// 时间轴
function timeLineInit(timeArray){
	var contentText = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.';
    var myjSonObject = {
        "args": {

        },
        "dataArray": timeArray
    }
    
    var pointWidth=Math.floor($("#myjtline").width()/timeArray.length)
    
    if(pointWidth>60){
    	pointWidth=60;
    }
    
    
    var jtLine = $('.myjtline').jTLine({
        // -------- Ajax Call -----------------
        // callType: 'ajax',
        // url: 'js/data.json',
        // -------- jSon Object ---------------
        callType: 'jsonObject',
        structureObj: myjSonObject,
        // -------- Maaped Json Object --------
        // map: {
        // "dataRoot": "/",
        // "title": "taskTitle",
        // "subTitle": "taskSubTitle",
        // "dateValue": "assignDate",
        // "pointCnt": "assignDate",
        // "bodyCnt": "taskDetails"
        // },
        // ------------------------------------
        distanceMode: 'fixDistance',// 'fixDistance' 'auto' 'predefinedDistance'
        eventsMinDistance: pointWidth,// Consider It as Distance Unit "by
										// Pixel"
        fixDistanceValue: 1, // if eventsMinDistance = 60 & fixDistanceValue=
								// 2 then the value is : 120 px
        firstPointMargin: 0.5,
        onPointClick: function (e) {
        	
           var pointTime=new String(e.target.textContent);
           var pointHour=pointTime.split(':')[0];
           var pointMinute=pointTime.replace(':','');
           remove_overlay(); 
           Heatmap.setPolygon(region);
           // 更改热力图数据
           if(cellUcList.length>0){			
   				Heatmap.setHeatMapData(cellUcList.filter(function(elt, i) {
   					var d = new String(elt.time);
   					if(d.length==10){   						
   						return d.substring(8,10)==pointHour;
   					}else{
   						return d.substring(8,12)==pointMinute;
   					}
   				}));
   			}
           $(".tlnode").each(function(){
        	    if($(this).text()==e.target.textContent){
        	    	startIndex=$(this).parent().index();
        	    }
           });
        }
    	/*
		 * , formatTitle: function (title) { return '<h2><span
		 * style="color:green">' + title + '</span></h2>'; }, formatSubTitle:
		 * function (subTitle) { return '<em><span style="color:blue">' +
		 * subTitle + '</span></em>'; }, formatBodyContent: function
		 * (bodyCnt) { return '<p><span style="color:#6a6a6a">' + bodyCnt + '</span></p>'; }
		 */

    });
}

function remove_overlay(){
	map.clearOverlays();         
}

var startIndex;
var t;
// 自动播放/暂停功能
Heatmap.autoPlay=function(startindex){
	ispause=true;
	$("#playButton").html("<i class='fa fa-pause'></i>&nbsp;暂停");
	if(startindex==null){
		startindex=startIndex;
	}
	$(".tlnode:eq("+startindex+")").click();
// var offset=((startindex+1)/timeArray.length)+0.008;
// $(".filling-line").first().css("transform", "scaleX("+offset+")");
	startindex=startindex+1;
	if(startindex==timeArray.length){
		startindex=0;
	}
	startIndex=startindex;
	t=setTimeout(function(){Heatmap.autoPlay(startIndex)},1000);
}

Heatmap.stopPlay=function(){
	ispause=false;
	$("#playButton").html("<i class='fa fa-play'></i>&nbsp;播放");
	$("#playButton").removeClass("btn-danger");
	clearTimeout(t);
}

Heatmap.play=function(){
	$("#playButton").toggleClass("btn-danger");
	if(ispause){
		Heatmap.stopPlay();
	}else{
		Heatmap.autoPlay();
	}
}

var ispause;
$(function () {
    /*
	 * var defaultColunms = Heatmap.initColumn(); var table = new
	 * BSTable(Heatmap.id, "/heatmap/list", defaultColunms);
	 * table.setPaginationType("client"); Heatmap.table = table.init();
	 */
	ztree = new $ZTree("areaTree", "/screening/tree");
	ztree.setSettings(setting);
    ztree.init();
    var zTreeObj = $.fn.zTree.getZTreeObj("areaTree");
    var nodes = zTreeObj.getCheckedNodes(true);
    zTreeObj.selectNode(nodes[0]);
    $("#selectArea").html(nodes[0].name);
    $(".dropdown-menu").on('click', function (e) {
        e.stopPropagation();
    });
	$('[data-toggle="popover"]').popover();
	
	$("#time").val(laydate.now(0, 'YYYY-MM-DD'));
	
	Heatmap.search();
	
	/*
	 * $("#playButton").toggle( function(){Heatmap.autoPlay()},
	 * function(){Heatmap.stopPlay()});
	 */
	ispause=false;
	
	
});
    